package com.thingcom.delinrobot.main.device;

import android.annotation.SuppressLint;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.android.tu.loadingdialog.LoadingDailog;
import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.gizwits.gizwifisdk.enumration.GizWifiDeviceNetStatus;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.thingcom.delinrobot.Common.Frame.ChangePinNum;
import com.thingcom.delinrobot.Common.Frame.FrameUtils;
import com.thingcom.delinrobot.Common.pjo.FrameType;
import com.thingcom.delinrobot.Data.GizManger;
import com.thingcom.delinrobot.R;
import com.thingcom.delinrobot.base.BaseBackFragment;
import com.thingcom.delinrobot.utils.HexStrUtils;
import com.thingcom.delinrobot.utils.MyLog;
import com.thingcom.delinrobot.utils.ToastUtil;
import com.thingcom.delinrobot.view.SimpleToolbar;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import static com.thingcom.delinrobot.utils.AppUtils.hideSoftKeyboard;

/**
 * author : YuFeng
 * e-mail : 923462992@qq.com
 * date   : 2019/11/21
 */
public class ChangePinBackFragment extends BaseBackFragment implements GizManger.myGizWifiDeviceListener{

    @BindView(R.id.toolbar_pin_change)
    SimpleToolbar toolbarPinChange;
    @BindView(R.id.btn_pin_sure)
    Button btnPinSure;
    @BindView(R.id.et_pin_old)
    TextInputEditText etPinOld;
    @BindView(R.id.til_pin_old)
    TextInputLayout tilPinOld;
    @BindView(R.id.et_pin_new)
    TextInputEditText etPinNew;
    @BindView(R.id.til_pin_new)
    TextInputLayout tilPinNew;
    @BindView(R.id.et_pin_new_again)
    TextInputEditText etPinNewAgain;
    @BindView(R.id.til_pin_new_again)
    TextInputLayout tilPinNewAgain;
    @BindView(R.id.cl_pin_change)
    ConstraintLayout clPinChange;
    private LoadingDailog dialog;

    public static ChangePinBackFragment newInstance() {
        Bundle bundle = new Bundle();
        ChangePinBackFragment fragment = new ChangePinBackFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_back_pin_change, container, false);
        unbinder = ButterKnife.bind(this, view);
        ColorStateList colorStateList = getResources().getColorStateList(R.color.text_input_edit_selectoe);
        tilPinOld.setBoxStrokeColorStateList(colorStateList);
        tilPinNew.setBoxStrokeColorStateList(colorStateList);
        tilPinNewAgain.setBoxStrokeColorStateList(colorStateList);
        //initToolbar(toolbarPinChange);
        etPinOld.setInputType(EditorInfo.TYPE_CLASS_PHONE);
        etPinNew.setInputType(EditorInfo.TYPE_CLASS_PHONE);
        etPinNewAgain.setInputType(EditorInfo.TYPE_CLASS_PHONE);
        toolbarPinChange.setMyLeftIcon(R.drawable.toolbar_back_two_selector);
        toolbarPinChange.setMinimumHeight(42);
        toolbarPinChange.setBackgroundColor(getResources().getColor(R.color.black_main));
        toolbarPinChange.setTitleStyle(getResources().getColor(R.color.white_main),13);
        toolbarPinChange.setLeftIconClickListener(view1 -> {
            hideSoftKeyboard(_mActivity);
            start(DeviceMainFragment.newInstance(),3);
        });
        clPinChange.setOnTouchListener((v, event) -> {
            clPinChange.clearFocus();
            hideSoftKeyboard(getContext(),clPinChange);
            return false;
        });
        Log.i("生命周期", "onCreateView: "+this.toString());
        GizManger.getInstance().setmCallback(this);
        return view;
    }

    @Override
    public boolean onBackPressedSupport() {
        start(DeviceMainFragment.newInstance(),3);
        return true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer!=null){
            timer.cancel();
        }
        MyLog.i("生命周期", "onDestroy: "+this.toString());
    }

    @OnClick(R.id.btn_pin_sure)
    public void onViewClicked() {
        String oldPsw = Objects.requireNonNull(etPinOld.getText()).toString();
        String newPsw = Objects.requireNonNull(etPinNew.getText()).toString();
        String newPswAgain = Objects.requireNonNull(etPinNewAgain.getText()).toString();
        if (oldPsw.length()!=4||newPsw.length()!=4){
            ToastUtil.showToast(getContext(),getString(R.string.toast_pin_number));
            return;
        }
        if (!newPsw.equals(newPswAgain)){
            ToastUtil.showToast(getContext(),getString(R.string.toast_two_input));
            return;
        }
        Log.i("pin输入", "onViewClicked: "+oldPsw+newPsw);
        byte[] dataPsw = new byte[8];
        for (int i =0;i<4;i++){
            String perPsw = oldPsw.substring(i,i+1);
            String perNewPsw = newPsw.substring(i,i+1);
            dataPsw[i] = Byte.parseByte("0"+perPsw);
            dataPsw[i+4] =  Byte.parseByte("0"+perNewPsw);
        }
        ChangePinNum changePinNum =new ChangePinNum("00000000",dataPsw);
        GizManger.getInstance().GizWrite(changePinNum.parse());
        LoadingDailog.Builder loadBuilder=new LoadingDailog.Builder(getContext())
                .setCancelable(false)
                .setCancelOutside(false);
        dialog=loadBuilder.create();
        dialog.show();
        timer.start();
    }

    @Override
    public void didSetSubscribe(GizWifiErrorCode result, GizWifiDevice device, boolean isSubscribed) {

    }

    @Override
    public void didReceiveData(GizWifiErrorCode result, GizWifiDevice device, ConcurrentHashMap<String, Object> dataMap, int sn) {
        if (dataMap.get("binary") != null) {
//            ConcurrentHashMap<String, Object> map = (ConcurrentHashMap<String, Object>) dataMap.get("binary");
            // 扩展数据点，key为"kuozhan"
            byte[] bytes = (byte[]) dataMap.get("binary");
            byte[] dataArea;
            FrameType identify = FrameUtils.getDataIdentifyEnum(bytes);
            MyLog.i("1234", "didReceiveData: " + identify);
            if(identify == FrameType.TYPE_FRAME_ROBOT_PIN_CHANGE){
                dataArea = FrameUtils.getDataArea(bytes);
                String dataA = HexStrUtils.bytesToHexString(dataArea);
                MyLog.i("1234", "didReceiveData: " + dataA);
                if (timer!=null){
                    timer.cancel();
                }
                if (dialog!=null){
                    dialog.dismiss();
                }
                if (dataA.equals("01")){
                    start(DeviceMainFragment.newInstance(),3);
                    Toast.makeText(getContext(),getString(R.string.success_toast), Toast.LENGTH_SHORT).show();
                    hideSoftKeyboard(getContext(), tilPinNewAgain);
                } else {
                    Toast.makeText(getContext(),(R.string.fail_toast), Toast.LENGTH_SHORT).show();
                }
            }
            String string = HexStrUtils.bytesToHexString(bytes);
            MyLog.i("收到数据","string:"+string);
//            Toast.makeText(getContext(), string, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void didGetHardwareInfo(GizWifiErrorCode result, GizWifiDevice device, ConcurrentHashMap<String, String> hardwareInfo) {

    }

    @Override
    public void didSetCustomInfo(GizWifiErrorCode result, GizWifiDevice device) {

    }

    @Override
    public void didUpdateNetStatus(GizWifiDevice device, GizWifiDeviceNetStatus netStatus) {

    }

    private CountDownTimer timer = new CountDownTimer(10000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
        }

        @Override
        public void onFinish() {
            Toast.makeText(getContext(), R.string.time_out,Toast.LENGTH_SHORT).show();
            if (dialog!=null){
                dialog.dismiss();
            }
        }
    };
}
